package com.wenjiang.controller;

import com.wenjiang.entity.User;
import com.wenjiang.service.userservice;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController  //返回josn
@RequestMapping("user")
@CrossOrigin//允许跨域访问
public class usercontroller {
    @Autowired
    private userservice userservice;
    //查询所有方法
    @RequestMapping("findall")
    public List<User> findall()
    {
        List<User> users=userservice.findall();

        return users;
    }

    //保存用户的方法
    @PostMapping ("save")
    public Map<String,Object> save(@RequestBody User user)
    {
        Map<String,Object> map=new HashMap<String,Object>();

        try {
            System.out.println(user.getId());
            if (StringUtils.isEmpty(user.getId()))
            {
                userservice.saveuser(user);
            }
            else
            {
                userservice.updateuser(user);
            }
            map.put("success",true);
        }
        catch (Exception e)
        {
            map.put("success",false);
            map.put("message","保存或更新用户信息失败!");
            System.out.println(e);
        }
        return map;

    }

    //删除方法
    @GetMapping("delete")
    public Map<String,Object> delete(String id)
    {
        Map<String,Object> map= new HashMap<String,Object>();
        try {
            userservice.deleteuser(id);
            map.put("success",true);
        }catch (Error e)
        {
            map.put("success",false);
            map.put("message","删除失败");
        }
        return map;

    }

    //查询一个的方法
    @GetMapping("finduserbyid")
    public User findbyid(String id)
    {
        return userservice.findbyid(id);
    }

    //模糊查询方法
    @GetMapping("findlike")
    public List<User> findnameorcode(String name, String code)
    {
        return userservice.finanameorphone(name,code);
    }
}
